package com.swjd.search;

import java.util.Arrays;

/**
 * 斐波那契查找
 *
 * @author 刘涛
 * @create 2021/9/30 10:27
 */
public class FibonacciSearch {
    public static void main(String[] args) {
        int arr[] = {1, 8, 10, 89, 1000, 1234};
        System.out.println(fibSearch(arr,89));
    }

    //创建一个斐波那契数列
    public static int[] fib() {
        int[] f = new int[20];
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i < f.length; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        return f;
    }

    /**
     * 斐波那契查找
     *
     * @param arr 数组
     * @param vul 查找的值
     * @return 查找到的下标
     */
    public static int fibSearch(int[] arr, int vul) {
        int left = 0;
        int right = arr.length - 1;
        int k = 0;//斐波那契分割数值的下标
        int center = 0;//中间值
        int f[] = fib();//获取斐波那契数列
        while (right > f[k] - 1) {
            k++;
        }
        //拷贝arr的第f[k]个数据
        int[] temp = Arrays.copyOf(arr, f[k]);
        for (int i = right + 1; i < temp.length; i++) {
            temp[i] = arr[right];
        }
        //找到值
        while (left <= right) {
            center = left + f[k - 1] - 1;
            if (vul < temp[center]) {
                //向左查找
                right = center - 1;
                k--;
            } else if (vul > temp[center]) {
                //向右查找
                left = center + 1;
                k -= 2;
            } else {
                //找到
                if (center <= right) {
                    return center;
                } else {
                    return right;
                }
            }
        }
        return -1;
    }
}
